import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { fromJS } from 'immutable'
import moment from 'moment'

import { intl } from '../../../intl/intl'
import { formatContractPriceDecimal, formatDecimal, formatValue } from '../../../utils/dataUtils'

import Button from '../../../component/button/Button'
import Pagination from '../../../component/pagination/Pagination'
import Loading from '../../../component/loading/Loading'
import themeHOC from '../../common/themeHOC'

import { pollCurrentOrder, queryCurrentOrder, setCurrentOrderEnabled, revokeOrder } from '../../../redux/actions/tradeDataQueryAction'

@connect((state) => {
  return {
    currentContract: state.trade.market.get('currentContract'),
    contracts: state.trade.market.get('contracts'),
    currentOrderLoading: state.trade.dataQuery.get('currentOrderLoading'),
    currentOrderCurrentPage: state.trade.dataQuery.get('currentOrderCurrentPage'),
    currentOrderTotalPage: state.trade.dataQuery.get('currentOrderTotalPage'),
    currentOrderList: state.trade.dataQuery.get('currentOrderList')
  }
}, (dispatch) => {
  return bindActionCreators({
    pollCurrentOrder, revokeOrder, queryCurrentOrder
  }, dispatch)
})
@themeHOC
class CurrentOrder extends Component {
  componentDidMount () {
    const { currentContract, pollCurrentOrder } = this.props
    pollCurrentOrder(currentContract, 1)
  }

  componentDidUpdate (prevProps, prevState, snapshot) {
    const { currentContract, pollCurrentOrder } = this.props
    if (formatValue(prevProps.currentContract, 'InstrumentID') !== formatValue(currentContract, 'InstrumentID')) {
      pollCurrentOrder(currentContract, 1)
    }
  }

  componentWillUnmount () {
    setCurrentOrderEnabled(false)
  }

  /**
   * 撤单
   * @param order
   * @returns {function(...[*]=)}
   */
  revokeOrderClick = order => () => {
    const { currentContract, currentOrderCurrentPage, revokeOrder, queryCurrentOrder } = this.props
    revokeOrder(order, () => {
      queryCurrentOrder(currentContract, currentOrderCurrentPage)
    })
  }

  renderPagination () {
    const {
      theme, currentContract, currentOrderLoading, currentOrderCurrentPage,
      currentOrderTotalPage, currentOrderList, pollCurrentOrder
    } = this.props
    if (currentOrderList.size !== 0 || !currentOrderLoading) {
      return (
        <Pagination
          theme={theme}
          className="trade-data-query-table-pagination"
          currentPage={currentOrderCurrentPage}
          totalPage={currentOrderTotalPage}
          onPageChange={(pageIndex) => { pollCurrentOrder(currentContract, pageIndex) }}/>
      )
    }
  }

  renderLoading () {
    if (this.props.currentOrderLoading) {
      return <Loading className="trade-data-query-table-loading"/>
    }
  }

  renderEmpty () {
    const { currentOrderLoading, currentOrderList } = this.props
    if (!currentOrderLoading && currentOrderList.size === 0) {
      return <p className="trade-data-query-table-no-data">{intl('no_data')}</p>
    }
  }

  renderTableContent () {
    const { contracts, currentOrderList } = this.props
    return currentOrderList.map((order, index) => {
      const id = formatValue(order, 'InstrumentID')
      const contract = formatValue(contracts, id, fromJS({}))
      const isBuy = formatValue(order, 'Direction') === 48
      const buySell = isBuy ? 'buy' : 'sell'
      const isOpen = formatValue(order, 'OffsetFlag') === '0'
      const tradeVolume = formatValue(order, 'VolumeTraded', 0)
      const turnover = formatValue(order, 'Turnover')
      const isInverse = formatValue(contract, 'IsInverse', 0)
      const volumeMultiple = formatValue(contract, 'VolumeMultiple', 1)
      const averagePrice = isInverse ? tradeVolume * volumeMultiple / turnover : turnover / tradeVolume / volumeMultiple
      return (
        <tr key={`current_order_${index}`}>
          <td>{id}</td>
          <td
            datatype={buySell}>
            {
              isOpen
                ? (isBuy ? intl('buy_open_long') : intl('sell_open_short'))
                : (isBuy ? intl('buy_close_short') : intl('sell_close_long'))
            }
          </td>
          <td>
            {moment(formatValue(order, 'InsertTime') * 1000).format('YYYY-MM-DD hh:mm:ss')}
          </td>
          <td>{formatValue(order, 'Volume')}</td>
          <td>{formatContractPriceDecimal(contract, formatValue(order, 'LimitPrice'))}</td>
          <td>{tradeVolume}</td>
          <td>{tradeVolume === 0 ? '--' : formatContractPriceDecimal(contract, averagePrice)}</td>
          <td>{formatDecimal(formatValue(order, 'FrozenMargin'), 8)}</td>
          <td>{formatDecimal(formatValue(order, 'Fee'), 8)}</td>
          <td>
            <Button onClick={this.revokeOrderClick(order)}>{intl('revoke_order')}</Button>
          </td>
        </tr>
      )
    })
  }

  render () {
    return (
      <div className="trade-data-query-table-container">
        <table>
          <thead>
            <tr>
              <td>{intl('name')}</td>
              <td>{intl('direction')}</td>
              <td>{intl('order_time')}</td>
              <td>{intl('order_volume')}</td>
              <td>{intl('order_price')}</td>
              <td>{intl('trade_volume')}</td>
              <td>{intl('trade_average_price')}</td>
              <td>{intl('frozen_margin')}</td>
              <td>{intl('fee')}</td>
              <td>{intl('operator')}</td>
            </tr>
          </thead>
          <tbody>
            {this.renderTableContent()}
          </tbody>
        </table>
        {this.renderLoading()}
        {this.renderPagination()}
        {this.renderEmpty()}
      </div>
    )
  }
}

export default CurrentOrder
